package action;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import common.Helper;
import table.EvalHandle;
import table.Evaluation;
import table.User;

/**
 * 更新评价的控制器
 */
@WebServlet("/UpdateEvaluation")
public class UpdateEvaluation extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateEvaluation() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 使用get访问该页无效
		response.getWriter().append("Please use POST method!");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 用户登录有效性验证段
		User user = (User) request.getSession().getAttribute("user");
		if(user == null){
			request.getRequestDispatcher("index.jsp").forward(request, response);
				return;
		}
						
		int eeid = Integer.parseInt(request.getParameter("eeid"));
		EvalHandle handle = new EvalHandle();
		List<Evaluation> list = handle.getEvalsOfUserInEe(user.getId(), eeid);
		for(int i=0; i<list.size(); i++) {
			int score = Integer.parseInt(Helper.getString(request.getParameter("num_score_" + i)));
			String remark = Helper.getString(request.getParameter("txt_eval_" + i));
			list.get(i).setScore(score);
			list.get(i).setRemark(remark);
		}
		int count = handle.updateEvalsToDB(list);
		if(count != 0) {
			//如果修改成功则返回之前修改页面，并弹出成功修改了多少条评价信息
			response.getWriter().println("<script>window.location.href='user_edit_evaluation.jsp?eeid=" + eeid + "';alert('sucessfully updata "+ count +" evaluations');</script>");
		}else {
			// 如果修改失败则返回之前修改页面，并弹出修改失败
			response.getWriter().println("<script>window.location.href='user_edit_evaluation.jsp?eeid" + eeid + "';alert('Fail to modify!');</script>");
		}
	}

}
